<template>
  <div id="login" v-show="loginisShow">
    <div v-show="issignupDialog || issetPassword" class="topTitle">
      <img :src="OemUrl.show ? OemUrl.url : require('../../assets/images/erplogo.svg')" class="erplogo" alt="" srcset="" v-show="OemUrl.requestEnd" />
      <span class="cz_span">
        <span class="_span hoverToBlue" @click="goLogin">登 录</span>
        <span class="hx">|</span>
        <span class="_span hoverToBlue" @click="goRegister">注 册</span>
      </span>
    </div>
    <div class="loginBody" :class="{ loginBody1: NODE_ENV != 'checkTest' }" v-show="!issignupDialog && !issetPassword">
      <div class="login_header" v-if="NODE_ENV == 'checkTest'">
        <img :src="OemUrl.show ? OemUrl.url : require('../../assets/images/portal_login.svg')" class="logo" alt="" srcset="" v-show="OemUrl.requestEnd" />
        <el-tabs v-model="navName" @tab-click="handleClick" class="navtabs">
          <el-tab-pane v-for="item in portalnavS" :key="item.id" :label="item.label" :name="item.name"></el-tab-pane>
        </el-tabs>
        <div class="header_r">
          <span @click="isLoginInput = !isLoginInput">登录</span>
          <span class="trial" @click="goRegister">免费试用</span>
        </div>
      </div>
      <img v-else :src="OemUrl.show ? OemUrl.url : require('../../assets/images/erplogo.svg')" class="logoErp" alt="" srcset="" v-show="OemUrl.requestEnd" />

      <div class="card" v-show="NODE_ENV != 'checkTest' || isLoginInput">
        <div class="tabs" v-if="!isQrCode">
          <el-tabs v-model="activeName" :class="{ 'tabs-none': activeName === 'wechat' || activeName === 'select' }">
            <template v-if="activeName !== 'select'">
              <template v-if="!code">
                <el-tab-pane name="account">
                  <span slot="label"><i class="iconfont">&#xe644;</i> 账号密码登录</span>
                  <!-- @signup点击注册  @accountLoginSuccess账号密码登录成功 -->
                  <login-account @QrCode="onQrCode" ref="account" v-if="activeName == 'account'" @expire="expireShow" @signup="onSignup" @accountLoginSuccess="getSetToken" @ResetPasswordFun="ResetPasswordFun" />
                </el-tab-pane>
                <el-tab-pane name="phone">
                  <span slot="label"><i class="iconfont">&#xe840;</i> 手机号登录</span>
                  <!-- @selectEnterprise该手机号有多个企业开始选择企业 -->
                  <login-phone @QrCode="onQrCode" ref="phone" v-if="activeName == 'phone'" @expire="expireShow" @signup="onSignup" @selectEnterprise="showSelectEnterprise" @phoneLoginSuccess="getSetToken" @ResetPasswordFun="ResetPasswordFun" />
                </el-tab-pane>
              </template>
              <el-tab-pane name="wechat" v-if="OemUrl.requestEnd && !OemUrl.show">
                <span slot="label" v-if="!code"><i class="iconfont">&#xe645;</i> 微信扫码</span>
                <div class="box">
                  <div id="qrcode" v-loading="l1">
                    <img class="img1" v-if="qrCode && !isTimer" :src="qrCode" alt="" />
                    <img class="img1" v-else-if="qrCode && isTimer" src="@/assets/images/timer.svg" alt="" />
                    <div v-else class="d"></div>
                    <div v-if="!isSuccess && !isTimer" class="tx">请使用微信扫描二维码登录</div>
                    <div v-if="isSuccess" class="tx"><img class="img2" src="@/assets/images/dui.svg" alt="" /> 扫码成功， 请在微信中点击授权登录</div>
                    <div v-if="isTimer" class="tx">二维码超时，请<span style="color: #5eb2eb; cursor: pointer" @click="onQrCode"> 重试 </span></div>
                  </div>
                  <!-- <div class="foot">
                    <div class="txt" @click="switchType1(1)">账号密码登录</div>
                    <span class="line"></span>
                    <div class="txt" @click="switchType1(2)">手机号登录</div>
                  </div> -->
                </div>
              </el-tab-pane>
            </template>
            <el-tab-pane v-else label="请选择企业" name="select">
              <!-- enterpriseList企业列表 -->
              <select-enterprise :enterpriseList="enterpriseList" @selectLoginSuccess="getSetToken" @expire="expireShow"/>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="box" v-else>
          <div class="title edit1">微信扫码</div>
          <div id="qrcode" v-loading="l1">
            <img v-if="qrCode" :src="qrCode" alt="" />
          </div>
          <div class="foot">
            <div class="txt" @click="switchType1(1)">账号密码登录</div>
            <span class="line"></span>
            <div class="txt" @click="switchType1(2)">手机号登录</div>
          </div>
        </div>
      </div>
      <div class="portalbody" v-if="NODE_ENV == 'checkTest'">
        <iframe :src="portalSrc" style="width: 100%; height: 100%" frameborder="0" />
      </div>
    </div>
    <div class="footer" v-if="!OemUrl.show">北京云代账互联网科技有限公司版权所有 <a href="https://beian.miit.gov.cn" target="_blank">京ICP备16066022号-5</a></div>
    <!-- 注册dialog -->
    <signup-dialog v-show="issignupDialog" @goLogin="goLogin" />
    <!-- 选择体验版本dialog  companynumber企业号  @selectVersionSuccess选择版本成功后 -->
    <select-version :isSelectVersion.sync="isTry" :companynumber="companynumber" @selectVersionSuccess="getSetToken" />
    <!-- 忘记密码 -->
    <ResetPassword @Reset="Reset" v-show="issetPassword" @verification="verification" ref="RPassword"></ResetPassword>
    <expire :dialogVisible="expireData.isExpire" :enterpriseNum="expireData.companynumber" :version="expireData.versionTypeDesc" @expireClose="expireClose" />
  </div>
</template>
<script>
import loginAccount from "./components/loginAccount.vue";
import loginPhone from "./components/loginPhone.vue";
import signupDialog from "./components/signupDialog.vue";
import selectVersion from "./components/selectVersion.vue";
import selectEnterprise from "./components/selectEnterprise.vue";
import ResetPassword from "./components/ResetPassword.vue";
import useLogin from "./mixins/useLogin";
import portalJS from "./mixins/portal";
import { mixinsMethod } from "@/util/util";
import instance from "@/config/http";
import "./plugins/awsc";
import { getBrowser, getOS } from "@/util/navigator";
import expire from "./components/expire.vue";

export default {
  name: "login",
  components: {
    loginAccount,
    loginPhone,
    signupDialog,
    selectVersion,
    selectEnterprise,
    ResetPassword,
    expire,
  },
  data() {
    return {
      l1: false,
      isQrCode: false,
      issignupDialog: false, //注册弹窗
      activeName: "account", //tabs
      companynumber: "", //选择体验版本的dialog需要使用
      isTry: false, //选择体验版本的dialog,
      enterpriseList: [], // 企业列表
      code: "", //微信首次登录的code
      issetPassword: false,
      loginisShow: false,
      qrCode: "",
      timer: null,
      isTimer: false,
      isSuccess: false,
      IsresetPassword: false,
      NODE_ENV: process.env.NODE_ENV,
      OemUrl: {
        url: "",
        show: false,
        requestEnd: false,
      },
      expireData: {}, //到期弹窗所需数据
    };
  },
  watch: {
    async activeName(newVal) {
      if (newVal !== "wechat") {
        if (this.timer) {
          clearInterval(this.timer);
          this.isTimer = false;
          this.isSuccess = false;
        }
      } else {
        this.onQrCode();
      }

      // this.isQrCode = true;
    },
  },
  mixins: [mixinsMethod, useLogin, portalJS],
  created() {
    this.getOemInfo();
    this.issignupDialog = sessionStorage.getItem("issignupDialog") == "true" ? true : false;
    this.issetPassword = sessionStorage.getItem("issetPassword") == "true" ? true : false;
    this.GetProvinces();

    let token = this.getQueryVariable("token"); // 财务大管家登录
    if (token) {
      const windowTitle = this.getQueryVariable("windowTitle");
      if (windowTitle) {
        document.title = window.decodeURI(windowTitle);
        sessionStorage.setItem("windowTitle", window.decodeURI(windowTitle));
      }
      this.singleLogin(token);
      return;
    }

    if (this.paramsList.every((e) => window.location.href.toString().indexOf(e) != -1)) {
      // 第三方跳转登录
      let params = {};
      this.paramsList.map((param) => {
        params[param] = this.cutUrlParams(param);
      });
      this.loginCustomer(params);
      return;
    }

    this.loginisShow = true;
    this.loginCode(); //微信扫码跳转的 code登录
    this.instantiationVnc(); // 实例化nvc 对无痕验证进行初始化操作
  },
  methods: {
    expireClose() {
      this.expireData.isExpire = false;
      if (this.activeName == "wechat") {
        this.onQrCode();
      }
    },
    expireShow(data) {
      this.expireData = data;
    },
    getOemInfo() {
      const Secret = this.getQueryVariable("Secret");
      if (Secret) {
        this.$api.publicApi
          .AgentLonginOem({ Secret })
          .then((res) => {
            console.log(res, "res");
            if (res.data.data.isOK) {
              sessionStorage.setItem("Secret", Secret);
              sessionStorage.setItem("windowTitle", res.data.data.titleName);
              this.OemUrl.url = res.data.data.oemUrl;
              this.OemUrl.show = true;
              this.OemUrl.requestEnd = true;
              this.setTitle(res.data.data.titleName);
            } else {
              this.setTitle();
              this.OemUrl.requestEnd = true;
            }
          })
          .catch(() => {
            this.setTitle();
            this.OemUrl.requestEnd = true;
          });
      } else {
        this.OemUrl.requestEnd = true;
        this.setTitle();
      }
    },
    setTitle(title) {
      document.title = title || "账三丰";
    },
    verification(e) {
      this.IsresetPassword = true;
    },
    switchType1(type) {
      if (type == 1) {
        this.isQrCode = false;
        this.activeName = "account";
      }
      if (type == 2) {
        this.isQrCode = false;
        this.activeName = "phone";
      }
      clearInterval(this.timer);
    },
    async onQrCode() {
      this.l1 = true;
      const { data } = await this.$api.publicApi.LoginQRcode({ clientExplorer: `${getOS()};${getBrowser()}` });
      this.qrCode = data.data.qrCode;
      if (this.timer) {
        clearInterval(this.timer);
        this.isTimer = false;
        this.isSuccess = false;
      }
      this.l1 = false;

      this.timer = setInterval(async () => {
        const { data: res } = await this.$api.publicApi.CheckUserLogin({ uniquenessCode: data.data.uniquenessCode });
        if (res.status == 424) {
          this.expireShow(res.data);
          clearInterval(this.timer);
          return;
        }
        const { message: msg } = res;
        if (msg == "二维码超时") {
          this.isTimer = true;
          this.isSuccess = false;
          clearInterval(this.timer);
        }
        if (msg == "扫码成功") {
          this.isTimer = false;
          this.isSuccess = true;
        }
        if (!Object.keys(res.data).length) return;
        clearInterval(this.timer);
        const { loginUser, tokenView } = res.data;
        this.getSetToken({ data: { userinfo: loginUser }, access_token: tokenView.access_token.slice(7) });
      }, 2000);
    },
    singleLogin(token) {
      // 财务大管家跳登录
      instance.defaults.headers["Authorization"] = "Bearer " + token;
      this.$api.publicApi.GetLoginUserInfo().then((res) => {
        let resData = res.data.data;
        this.getSetToken({ data: { userinfo: resData }, access_token: token });
      });
    },
    instantiationVnc() {
      // 实例化nvc 对无痕验证进行初始化操作
      let that = this;
      let windows1 = window;
      // eslint-disable-next-line no-undef
      AWSC.use("nvc", function (state, module) {
        // 实例化nvc 对无痕验证进行初始化操作 (每一次登录进行无痕验证)
        // 初始化 调用module.init进行初始化
        window.nvc = module.init({
          // test: module.TEST_NC_PASS,
          // 应用类型标识。它和使用场景标识（scene字段）一起决定了无痕验证的业务场景与后端对应使用的策略模型。您可以在阿里云验证码控制台的配置管理页签找到对应的appkey字段值，请务必正确填写。
          appkey: "FFFF0N0000000000A71A",
          //使用场景标识。它和应用类型标识（appkey字段）一起决定了无痕验证的业务场景与后端对应使用的策略模型。您可以在阿里云验证码控制台的配置管理页签找到对应的scene值，请务必正确填写。
          scene: "nvc_login",
          customWidth: 330,
          // 二次验证获取人机信息串，跟随业务请求一起上传至业务服务器，由业务服务器进行验签。
          success: function (data) {
            if (that.IsresetPassword) {
              that.$refs.RPassword.againGetCode(data);
            } else {
              window.console && console.log(data);
              console.log(window, windows1);
              if (that.activeName == "account") {
                // 账号密码登录
                that.$refs.account.loginAccount(data);
              }
              if (that.activeName == "phone") {
                // 手机号登录
                that.$refs.phone.loginPhone(data);
              }
              if (that.activeName == "wechat") {
                // 微信二维码绑定手机登录
                that.$refs.wechat.loginPhone(data);
              }
            }
          },
          // 前端二次验证失败时触发该回调参数
          fail: function (failCode) {
            window.console && console.log(failCode);
          },
          // 前端二次验证加载异常时触发该回调参数。
          error: function (errorCode) {
            window.console && console.log(errorCode);
          },
        });
      });
    },
    goLogin() {
      this.issignupDialog = false;
      this.issetPassword = false;
      sessionStorage.setItem("issignupDialog", false);
      sessionStorage.setItem("issetPassword", false);
    },
    goRegister() {
      sessionStorage.setItem("issignupDialog", true);
      sessionStorage.setItem("issetPassword", true);
      this.issignupDialog = true;
      this.issetPassword = false;
    },
    ResetPasswordFun() {
      // 忘记密码
      this.issetPassword = true;
      sessionStorage.setItem("issetPassword", true);
    },
    Reset() {
      // 重置
      this.issetPassword = false;
      sessionStorage.setItem("issetPassword", false);
    },
    onSignup() {
      // 注册dialog
      this.issignupDialog = true;
      sessionStorage.setItem("issignupDialog", true);
    },
    switchType(e) {
      //微信扫码底部     账号密码 | 手机号
      this.activeName = e;
    },
    showSelectEnterprise(enterpriseList) {
      // 手机号登录成功并且有多个企业则进入企业选择
      this.activeName = "select";
      this.enterpriseList = enterpriseList;
    },
    onWechat() {
      //右上角微信/。。图标
      this.activeName = this.activeName === "wechat" ? "account" : "wechat";
    },
    loginCode() {
      //获取查询参数
      const urlSearchParams = new URLSearchParams(window.location.search); // 创建一个URLSearchParams实例
      const params = Object.fromEntries(urlSearchParams.entries()); // 把键值对列表转换为一个对象
      if (params.code && params.state) {
        //存在code
        this.code = params.code;
        this.activeName = "wechat1";
      }
    },
    GetProvinces() {
      // 获取城市信息
      this.$api.publicApi.GetProvinces().then((res) => {
        let resData = res.data.data;
        let provinces = resData.provinces.sort(this.objectArraySort("proSort")); // 省
        let citys = resData.citys.sort(this.objectArraySort("citySort")); // 市
        let countys = resData.countys.sort(this.objectArraySort("id")); // 县
        citys.map((item) => {
          item.children ? "" : item.children = [];
          item.areaID = item.cityID;
          countys.map((items) => {
            if (item.cityID == items.cityID) {
              items.areaID = items.id;
              items.name = items.disName;
              item.children.push(items);
            }
          });
        });
        provinces.map((item) => {
          item.children ? "" : item.children = [];
          item.areaID = item.proID;
          citys.map((items) => {
            if (item.proID == items.proID) {
              item.children.push(items);
            }
            if (items.children && items.children.length == 0) {
              items.children = null;
            }
          });
        });
        this.$store.dispatch("getAddressList", provinces);
      });
    },
  },
};
</script>

<style lang="less" scoped>
:deep(.el-tabs) {
  .el-tabs__content {
    padding-top: 30px;
  }
}
:deep(.el-tabs__nav-next),
:deep(.el-tabs__nav-prev) {
  display: none;
}
:deep(.el-tabs__nav-wrap.is-scrollable) {
  padding: 0px;
}

:deep(.el-tabs__item) {
  padding: 0 12px;
}

:deep(#tab-none) {
  display: none;
}
:deep(.bar) {
  .sub-title {
    font-size: 12px;
    margin-left: 10px;
    font-weight: 500;
  }
}
:deep(.el-tabs__header) {
  margin: 0;
}
:deep(.el-tabs__item) {
  color: #333;
  font-size: 15px;
  line-height: 88px;
  height: 70px;
  color: #999;
}
:deep(.el-tabs__active-bar) {
  background-color: #6199f5;
}
:deep(.tabs-none) {
  .el-tabs__item {
  }
  .el-tabs__active-bar {
  }
}
:deep(.is-active) {
  color: #6199f5;
  // font-weight: bold;
}
#login {
  width: 100%;
  height: 100%;

  // position: relative;
  // background-image: url("../../assets/images/login_bq.png");
  // background-repeat: no-repeat; //不重复
  // background-size: 100% 100%; // 满屏
  .loginBody {
    width: 100%;
    height: 100%;
    position: relative;
    // background-image: url("../../assets/images/login_bq.png");
    // background-repeat: no-repeat; //不重复
    // background-size: 100% 100%; // 满屏
    .card {
      position: absolute;
      // top: 22%;
      // right: 11%;
      top: 80px;
      right: 130px;
      width: 380px;
      height: 420px;
      text-align: center;
      background-color: #ffffff;
      border-radius: 15px;
      -webkit-box-shadow: 0 3px 10px 2px #ccc;
      box-shadow: 0 3px 10px 2px #ccc;
      padding: 25px;
      padding-top: 0px;

      .tabs {
        position: relative;
        .font-pic {
          position: absolute;
          right: -15px;
          top: 10px;
          font-size: 50px;
          z-index: 99;
          color: #5b95f9;
          cursor: pointer;
          background: #ffff;
        }
        .box {
          padding-top: 15px;
          display: flex;
          // height: 100%;
          height: 315px;
          flex-direction: column;
          .title {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
          }
          #qrcode {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            .img1 {
              width: 200px;
              height: 200px;
            }
            .d {
              width: 200px;
              height: 200px;
            }
            .tx {
              font-size: 14px;
              color: #333;
              margin-top: 20px;
              display: flex;
              align-items: center;
              .img2 {
                width: 20px;
                height: 20px;
                margin-right: 10px;
              }
            }
          }
          .foot {
            margin-top: 30px;
            font-size: 13px;
            display: flex;
            align-items: center;
            justify-content: center;

            .line {
              width: 2px;
              height: 20px;
              margin: 0 20px;
              background: #99999930;
            }
            .txt {
              cursor: pointer;
              color: #999;
              &:hover {
                color: #5eb2eb;
              }
            }
          }
        }
      }
      .login-btn {
        width: 100%;
        margin-bottom: 50px;
        text-align: left;
        padding-left: 30px;

        .btn {
          width: 40%;
          height: 30px;
          font-size: 13px !important;
          line-height: 12px;
          margin-top: 11%;
          border-radius: 2px;
          font-weight: 600;
          transition: none;
        }
        :deep(._span) {
          margin-top: 50px;
          margin-left: 40px;
          font-size: 13px;
          &:hover {
            color: #5b95f9;
          }
        }
      }
      .login-btn-phone {
        display: flex;
        flex-direction: column;
        .btn {
          width: 80%;
          margin: 0 auto;
          height: 30px;
          font-size: 13px !important;
          line-height: 12px;
          margin-top: 12%;
          border-radius: 2px;
          font-weight: 600;
          transition: none;
        }
        :deep(._span) {
          margin-top: 7%;
          font-size: 13px;
          &:hover {
            color: #5b95f9;
          }
        }
      }
      .valid {
        margin-top: 23px;
        .valid-btn {
          width: 200px;
          height: 30px;
          font-size: 13px !important;
          line-height: 12px;
          border-radius: 2px;
          font-weight: 600;
          transition: none;
        }
      }
    }
    .login_header {
      height: 65px;
      background-color: #455064;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 60px;
      .logo {
        height: 36px;
      }
      .navtabs {
        :deep(.el-tabs__header) {
          height: auto !important;
        }
        :deep(.el-tabs__content) {
          display: none;
        }
        :deep(.el-tabs__nav-wrap::after, .el-tabs__active-bar) {
          height: 0;
        }
        :deep(.el-tabs__item) {
          font-size: 13px;
          line-height: 65px;
          height: 65px;
          color: #fff;
          font-weight: 300;
        }
        :deep(.is-active) {
          color: #45a9f0;
        }
        :deep(.el-tabs__active-bar) {
          background-color: #45a9f0;
        }
      }
      .header_r {
        color: #f6fbfe;
        font-size: 12px;
        font-weight: 300;
        > span {
          cursor: pointer;
        }
        .trial {
          display: inline-block;
          border-radius: 15px;
          border: 1px solid #f6fbfe;
          padding: 1px 10px;
          margin-left: 20px;
        }
      }
    }
    .portalbody {
      width: 100%;
      height: calc(100% - 65px);
    }
  }
  .loginBody1 {
    background-image: url("../../assets/images/login_bq.png");
    background-repeat: no-repeat; //不重复
    background-size: 100% 100%; // 满屏
    .card {
      top: 22%;
      right: 11%;
    }
    .tabs {
      .box {
        padding-top: 45px;
      }
    }
  }
  .logoErp {
    width: 160px;
    position: absolute;
    left: 38px;
    top: 18px;
    z-index: 100;
  }
  .topTitle {
    height: 65px;
    box-shadow: 0px 1px 15px rgb(224 224 224);
    position: relative;
    z-index: 1;
    .cz_span {
      position: absolute;
      // right: 58px;
      // top: 18px;
      right: 60px;
      top: 20.2px;
      z-index: 100;
      ._span {
        margin-left: 10px;
        font-size: 14px;
        color: #333;
        &:hover {
          color: #5b95f9;
        }
      }
      .hx {
        margin-left: 10px;
        color: #ccc;
      }
    }
    .erplogo {
      height: 36px;
      position: absolute;
      left: 60px;
      top: 14.5px;
      z-index: 100;
    }
  }
  .footer {
    position: absolute;
    bottom: 10px;
    left: 40%;
    font-size: 14px;
  }
}

.hidden {
  display: block;
  visibility: hidden;
}
</style>
